<template>
  <div class="app-container">


    <el-tabs type="border-card" style="margin-top: 20px;" @tab-click="onClickTab">

      <el-tab-pane>
        <el-button type="primary" class="el-icon-plus" @click="handleAddOrganize">组织架构</el-button>
        <span slot="label">部门管理</span>
        <el-table :data="organizeList" style="width: 100%;margin-top:30px;" border>
          <el-table-column align="center" label="Key" width="220">
            <template slot-scope="scope">
              {{ scope.row.key }}
            </template>
          </el-table-column>
          <el-table-column align="center" label="名称" width="220">
            <template slot-scope="scope">
              {{ scope.row.name }}
            </template>
          </el-table-column>
          <el-table-column align="center" label="编码" width="220">
            <template slot-scope="scope">
              {{ scope.row.kcode }}
            </template>
          </el-table-column>
          <el-table-column align="header-center" label="描述">
            <template slot-scope="scope">
              {{ scope.row.description }}
            </template>
          </el-table-column>
          <el-table-column align="center" label=操作>
            <template slot-scope="scope">
              <el-button type="primary" size="small" @click="handleEditOrganize(scope)">编辑</el-button>
              <el-button type="danger" size="small" @click="handleDeleteOrganize(scope)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-tab-pane>
      <el-tab-pane>
        <el-button type="primary" class="el-icon-plus" @click="handleAddRole">创建年级</el-button>
        <span slot="label"> 年级管理</span>
        <el-table :data="gradeList" style="width: 100%;margin-top:30px;" border>
          <el-table-column align="center" label="Key" width="220">
            <template slot-scope="scope">
              {{ scope.row.key }}
            </template>
          </el-table-column>
          <el-table-column align="center" label="年级名称" width="220">
            <template slot-scope="scope">
              {{ scope.row.name }}
            </template>
          </el-table-column>
          <el-table-column align="center" label="年级编码" width="220">
            <template slot-scope="scope">
              {{ scope.row.kcode }}
            </template>
          </el-table-column>
          <el-table-column align="center" label="学段" width="220">
            <template slot-scope="scope">
              {{ STAGE[scope.row.stage].label }}
            </template>
          </el-table-column>
<!--          <el-table-column align="center" label="组织架构" width="220">-->
<!--            <template slot-scope="scope">-->
<!--              {{ _getObjectByProp(scope.row.organize_code,'key',organizeList).name }}-->
<!--            </template>-->
<!--          </el-table-column>-->
          <el-table-column align="header-center" label="描述">
            <template slot-scope="scope">
              {{ scope.row.description }}
            </template>
          </el-table-column>
          <el-table-column align="center" label=操作>
            <template slot-scope="scope">
              <el-button type="primary" size="small" @click="handleEdit(scope)">编辑</el-button>
              <el-button type="danger" size="small" @click="handleDelete(scope)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>

      </el-tab-pane>
    </el-tabs>

    <!--    <el-dialog :visible.sync="dialogVisible" :title="dialogType==='edit'?'Edit Role':'New Role'">-->
    <el-dialog
      :title="dialogTitle[dialogType]"
      :visible.sync="dialogVisible"
      :close-on-click-modal=false
      top="5vh">

      <el-form
        ref=""
        :model="grade"
        :rules="rules"
        label-width="100px"
        style=" width: 80%; margin-left:50px;">
        <el-form-item label="年级：" prop="">
          <el-input v-model.trim="grade.name"></el-input>
          <!--              <span class="underInputWords">字母、数字、下划线</span>-->
        </el-form-item>
        <el-form-item label="学段：" prop="">
          <el-select v-model="grade.stage" placeholder="请选择学段">
            <el-option v-for="(item,index) in STAGE"
                       :label="item.label"
                       :value="index">
            </el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="年级编码：" prop="">
          <el-input v-model.trim="grade.kcode"></el-input>
           <span class="underInputWords">规则：格式统一不重复，例如：GL001，GL002..</span>
        </el-form-item>


        <el-form-item label="描述：" prop="describe">
          <!--              <el-input v-model.number="defaultOrder.describe"></el-input>-->
          <el-input
            type="textarea"
            placeholder="请输入内容"
            v-model="grade.description"
            maxlength="30"
            show-word-limit>
          </el-input>
        </el-form-item>
<!--        <el-form-item label="绑定班级：">-->
<!--          <el-tree-->
<!--            ref="tree"-->
<!--            :check-strictly="true"-->
<!--            :data="classList"-->
<!--            show-checkbox-->
<!--            node-key="path"-->
<!--            class="permission-tree"-->
<!--          />-->
<!--        </el-form-item>-->


        <el-form-item>
          <div style="text-align:right;">
            <el-button type="danger" @click="cancelConsumer">取消</el-button>
            <el-button type="primary" @click="confirmConsumer(dialogType)">确认</el-button>
          </div>
        </el-form-item>
      </el-form>

    </el-dialog>

    <el-dialog :visible.sync="dialogVisible_O" :title="dialogTitle[dialogType]" :close-on-click-modal=false>
      <el-form ref="formOrganize" :rules="rules" :model="organize" label-width="100px" label-position="left">
        <el-form-item label="名称：" prop="name">
          <el-input v-model="organize.name" placeholder="组织架构名称"/>
        </el-form-item>
        <el-form-item label="编码：" prop="name">
          <el-input v-model="organize.kcode" placeholder=""/>
          <span class="underInputWords">规则：格式统一不重复，例如：ORG001，ORG001..</span>
        </el-form-item>

        <el-form-item label="描述：">
          <el-input
            v-model="organize.description"
            :autosize="{ minRows: 2, maxRows: 4}"
            type="textarea"
            placeholder="描述"
          />
        </el-form-item>
        <el-form-item label="权限：">
          <el-tree
            ref="tree"
            :check-strictly="checkStrictly"
            :data="routesData"
            :props="defaultProps"
            show-checkbox
            node-key="path"
            class="permission-tree"
          />
        </el-form-item>
      </el-form>
      <div style="text-align:right;">
        <el-button type="danger" @click="dialogVisible_O=false">取消</el-button>
        <el-button type="primary" @click="confirmOrganize('formOrganize')">确定</el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script>
  import path from 'path'
  import { deepClone } from '@/utils'
  import { getObjectByProp } from '@/utils/utilc'
  import { deleteGradeSys, addGradeSys, getGradeSys, updateGradeSys } from '@/api/basicmgt'
  import { getOrganizes, addOrganize, deleteOrganize, updateOrganize } from '@/api/role'
  import { isInteger } from '@/utils/validate'

  const defaultGrade = {
    key: '',
    kcode: '',//年级编码（唯一）
    name: '',//年级名称
    stage:'',//学段 0小学，1 初中，2 高中
    // classnum: 0,//绑定班级数量
    // organize_code: '',//组织架构code
    description: ''
  }

  const defaultOrganize = {//这里的数据没啥用，只是让你知道格式
    key: '',          //
    name: '',         //角色名称
    kcode:'',         //编码（唯一）
    description: '',  //描述
    routes: []        //权限
  }

  export default {
    name: 'index',
    data() {
      return {

        rules: {
          organize: [{ required: true, message: '不能为空', trigger: 'blur' }],
          name: [{ required: true, message: '不能为空', trigger: 'blur' }],
          description: [{ required: true, message: '不能为空', trigger: 'blur' }]

          // order_type: [{ required: true, message: '请选择套餐', trigger: 'blur' }],
          // price: [{ required: true, message: '请输入数字', trigger: 'blur' }, { validator: isInteger, trigger: 'blur' }]
        },
        dialogTitle: ['创建', '编辑'],
        dialogVisible: false,
        dialogVisible_O: false,
        dialogType: '0',

        grade: Object.assign({}, defaultGrade),
        organize: Object.assign({}, defaultOrganize),//这里是部门分类创建
        STAGE:this.$global.STAGE,

        routes: [],
        gradeList: [],

        organizeList: this.$global.DEPARTMENT,

        checkStrictly: false,
        defaultProps: {
          children: 'children',
          label: 'title'
        },

        tabsName: [
          { key: 1, name: '角色管理' },
          { key: 2, name: '部门' }
        ],
        tabsNameIndex: 0

      }
    },
    computed: {
      routesData() {
        return this.routes
      }
    },
    created() {
      // Mock: get all routes and roles list from server
      // this.getRoutes()
      this.getGradeSys()
      this.getOrganizes()
    },
    methods: {
      // async getRoutes() {
      //   const res = await getRoutes()
      //   this.serviceRoutes = res.data
      //   this.routes = this.generateRoutes(res.data)
      // },
      async getGradeSys() {
        const res = await getGradeSys()
        console.log("res=="+JSON.stringify(res))
        this.gradeList = res.data
      },

      async getOrganizes() {
        const res = await getOrganizes()
        this.organizeList = res.data

      },

      _getObjectByProp(value, prop, array) {
        return getObjectByProp(value, prop, array)
      },

      onClickTab() {
        if (this.tabsNameIndex == 0) {

        } else if (this.tabsNameIndex == 1) {
          // this.dialogVisible_O = true

        }
      },

      // Reshape the routes structure so that it looks the same as the sidebar
      generateRoutes(routes, basePath = '/') {
        const res = []

        for (let route of routes) {
          // skip some route
          if (route.hidden) {
            continue
          }

          const onlyOneShowingChild = this.onlyOneShowingChild(route.children, route)

          if (route.children && onlyOneShowingChild && !route.alwaysShow) {
            route = onlyOneShowingChild
          }

          const data = {
            path: path.resolve(basePath, route.path),
            title: route.meta && route.meta.title

          }

          // recursive child routes
          if (route.children) {
            data.children = this.generateRoutes(route.children, data.path)
          }
          res.push(data)
        }
        return res
      },
      generateArr(routes) {
        let data = []
        routes.forEach(route => {
          data.push(route)
          if (route.children) {
            const temp = this.generateArr(route.children)
            if (temp.length > 0) {
              data = [...data, ...temp]
            }
          }
        })
        return data
      },
      handleAddRole() {
        this.grade = Object.assign({}, defaultGrade)
        if (this.$refs.tree) {
          this.$refs.tree.setCheckedNodes([])
        }
        this.dialogType = '0'
        this.dialogVisible = true;
      },
      handleAddOrganize() {
        this.organize = Object.assign({}, defaultOrganize)
        if (this.$refs.tree) {
          this.$refs.tree.setCheckedNodes([])
        }
        this.dialogType = '0'
        this.dialogVisible_O = true

      },
      handleEdit(scope) {
        this.dialogType = '1'
        this.dialogVisible = true
        this.grade = deepClone(scope.row)
        this.$nextTick(() => {
        })
      },

      handleEditOrganize(scope) {
        this.dialogType = '1'
        this.dialogVisible_O = true
        this.checkStrictly = true
        this.organize = deepClone(scope.row)
        this.$nextTick(() => {
          const routes = this.generateRoutes(this.grade.routes)
          this.$refs.tree.setCheckedNodes(this.generateArr(routes))
          // set checked state of a node not affects its father and child nodes
          this.checkStrictly = false
        })
      },

      handleDelete({ $index, row }) {
        this.$confirm('确定要删除年级吗?', '警告', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
          .then(async() => {
            await deleteGrade(row.key)
            this.gradeList.splice($index, 1)
            this.$message({
              type: 'success',
              message: 'Delete succed !'
            })
          })
          .catch(err => {
            console.error(err)
          })
      },

      handleDeleteOrganize({ $index, row }) {
        this.$confirm('确定要删除数据吗?', '警告', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
          .then(async() => {
            await deleteOrganize(row.key)
            this.organizeList.splice($index, 1)
            this.$message({
              type: 'success',
              message: 'Delete succed !'
            })
          })
          .catch(err => {
            console.error(err)
          })
      },

      generateTree(routes, basePath = '/', checkedKeys) {
        const res = []

        for (const route of routes) {
          const routePath = path.resolve(basePath, route.path)

          // recursive child routes
          if (route.children) {
            route.children = this.generateTree(route.children, routePath, checkedKeys)
          }

          if (checkedKeys.includes(routePath) || (route.children && route.children.length >= 1)) {
            res.push(route)
          }
        }
        return res
      },

      cancelConsumer(){
        this.dialogVisible=false
      },
      async confirmConsumer(type){
        if(type==0){//创建
          const { data } = await addGrade(this.grade)
          this.grade.key = data.key
          // console.log('创建==' + typeof this.orderList)
          this.gradeList.push(this.grade)
        }else{//edit
          await updateGrade(this.grade.key, this.grade)
          for (let index = 0; index < this.gradeList.length; index++) {
            if (this.gradeList[index].key === this.grade.key) {
              this.gradeList.splice(index, 1, Object.assign({}, this.grade))
              break
            }
          }
        }

        this.cancelConsumer()
      },

      async confirmOrganize(formOrganize) {
        let bool = false
        this.$refs[formOrganize].validate((valid) => {
          if (valid) {
            bool = true

          } else {
            this.$message('error submit!!')
            bool = false
          }
        })
        if (!bool) {

          return
        }
        const isEdit = this.dialogType === '1'

        // const checkedKeys = this.$refs.tree.getCheckedKeys()

        // this.grade.routes = this.generateTree(deepClone(this.serviceRoutes), '/', checkedKeys)

        if (isEdit) {
          await updateOrganize(this.organize.key, this.organize)

          for (let index = 0; index < this.organizeList.length; index++) {
            if (this.organizeList[index].key === this.organize.key) {
              this.organizeList.splice(index, 1, Object.assign({}, this.organize))
              break
            }
          }
        } else {
          const { data } = await addOrganize(this.organize)
          this.organize.key = data.key
          this.organizeList.push(this.organize)

          console.log('organizeList=' + JSON.stringify(this.organizeList))
        }

        const { description, key, name } = this.organize
        this.dialogVisible_O = false
        this.$notify({
          title: 'Success',
          dangerouslyUseHTMLString: true,
          message: `
            <div>Key: ${key}</div>
            <div>名称: ${name}</div>
            <div>描述: ${description}</div>
          `,
          type: 'success'
        })
      },

      // reference: src/view/layout/components/Sidebar/SidebarItem.vue
      onlyOneShowingChild(children = [], parent) {
        let onlyOneChild = null
        const showingChildren = children.filter(item => !item.hidden)

        // When there is only one child route, the child route is displayed by default
        if (showingChildren.length === 1) {
          onlyOneChild = showingChildren[0]
          onlyOneChild.path = path.resolve(parent.path, onlyOneChild.path)
          return onlyOneChild
        }

        // Show parent if there are no child route to display
        if (showingChildren.length === 0) {
          onlyOneChild = { ...parent, path: '', noShowingChildren: true }
          return onlyOneChild
        }

        return false
      }
    }
  }
</script>

<style lang="scss" scoped>
  .app-container {
    .roles-table {
      margin-top: 30px;
    }

    .permission-tree {
      margin-bottom: 30px;
    }
  }

  .underInputWords{
    font-size: small;
    color:#999!important;
    padding:0 5px!important}

</style>
<style>
  .el-table th {
    display: table-cell !important;
  }
</style>
